package com.ygxsk.carhome.ui.auth;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.AuthManageType;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.event.EventAuthMain;
import com.ygxsk.carhome.response.AuthManageItemOutSide;
import com.ygxsk.carhome.response.CarAttestation;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.sys.Session;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.AuthManageItemAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-22  16:10
 * @Description:认证管理，管理的主列表页:后台接口名称：员工端认证管理列表
 */
public class AuthManageListActivity extends ErrorActivity {

    @BindView(R.id.refreshlayoutinauthlist)
    SmartRefreshLayout refreshLayoutInAuthList;

    @BindView(R.id.recyclerviewinauthlist)
    RecyclerView recyclerViewInAuthList;

    //分配客户人员
//    @BindView(R.id.roundbuttonaddgroupinrunmangroup)
//    RoundTextView roundButtonAddGroupInRunManGroup;

//    //选择类型
//    @BindView(R.id.nice_spinner_type_auth)
//    NiceSpinnersk nice_spinner_type_auth;
//    //选择来源
//    @BindView(R.id.nice_spinner_auth_system)
//    NiceSpinnersk nice_spinner_auth_system;
//    //选择状态
//    @BindView(R.id.nice_spinner_state_item_auth)
//    NiceSpinnersk nice_spinner_state_item_auth;

    //潜在客户，
    private ArrayList<CarAttestation> mDataResources = new ArrayList<CarAttestation>();

    //筛选条件的 汽车的类型；
//    private ArrayList<NomalCustomBean> dataListAuthState = new ArrayList<NomalCustomBean>();
    //客户的来源
//    private ArrayList<NomalCustomBean> dataListFromWhere = new ArrayList();
    //该客户的分配状态
//    private ArrayList<NomalCustomBean> dataListCarType = new ArrayList();

    //适配器
    private AuthManageItemAdapter authManageItemAdapter;

    /**
     * 最后一条上传的id的信息内容
     */
    private int pagination_upLoad = Parameterkey.pageNum_default_first;


//    @OnClick({R.id.roundbuttonauthaddsubmit})//
//    public void onViewClickInAuthManage(View v) {
//
//        switch (v.getId()) {
//
//        	case R.id.roundbuttonauthaddsubmit: {
//                //添加车辆认证接口
//                Bundle extra_bundle = new Bundle();
//                ActivityUtils.startActivity(extra_bundle, AuthAddSubmitActivity.class);
//        	   break;
//              }
//
//            default:
//              break;
//        }
//
//    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        mSession = Session.get(this);

//        if (dataListAuthState == null) {
//            dataListAuthState = new ArrayList<>();
//        }

//        if (dataListStateItem == null) {
//            dataListStateItem = new ArrayList<>();
//        }

        initloading();

        initViews();

        gainDatas();

        //监听单个客户内容
        //列表之内需要向外部广播数据
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_auth_manage_list;
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.title_authmanage));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //添加潜在客户的按钮
        toolbarHelper.setLayoutRight(true, 1, getString(R.string.title_right_history), new ClickUtils.OnDebouncingClickListener() {
            @Override
            public void onDebouncingClick(View v) {

                //快速双加的限制，
                // TODO: 2023-07-11 16:18跳转到认证管理的历史记录
                Bundle extra_bundle = new Bundle();

                ActivityUtils.startActivity(extra_bundle, AuthManageHistoryActivity.class);

            }
        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {


        //----------------------------------------------------------------------------------
//        // : 2023-07-14 09:23 测试类型数据
//        NomalCustomBean nomalCustomBean = new NomalCustomBean();
//        nomalCustomBean.setDictCode("1");
//        nomalCustomBean.setDictLabel("新车");
//
//        NomalCustomBean nomalCustomBean1 = new NomalCustomBean();
//        nomalCustomBean1.setDictCode("2");
//        nomalCustomBean1.setDictLabel("二手车");
//
//        dataListAuthState.add(nomalCustomBean);
//        dataListAuthState.add(nomalCustomBean1);

        //直接存储mmkv的信息
//        MMKV.defaultMMKV().encode(ConstantSign.MMKV_JSON_CAR_TYPES_JSON, JSON.toJSONString(dataListAuthState));

        //初始化 选择类型
//        method_spinnser_auth_type();

        //----------------------------------------------------------------------------------

//        LeadFromWhereBean leadFromWhereBean = new LeadFromWhereBean();
//        leadFromWhereBean.setDictType("1");
//        leadFromWhereBean.setDictLabel("预约看车");
//
//        LeadFromWhereBean leadFromWhereBean1 = new LeadFromWhereBean();
//        leadFromWhereBean1.setDictType("2");
//        leadFromWhereBean1.setDictLabel("预约试驾");
//
//        LeadFromWhereBean leadFromWhereBean2 = new LeadFromWhereBean();
//        leadFromWhereBean2.setDictType("3");
//        leadFromWhereBean2.setDictLabel("自然到店");
//
//        LeadFromWhereBean leadFromWhereBean3 = new LeadFromWhereBean();
//        leadFromWhereBean3.setDictType("4");
//        leadFromWhereBean3.setDictLabel("服务站推荐");
//
//        dataListFromWhere.add(leadFromWhereBean);
//        dataListFromWhere.add(leadFromWhereBean1);
//        dataListFromWhere.add(leadFromWhereBean2);
//        dataListFromWhere.add(leadFromWhereBean3);
//
//        //直接存储mmkv的信息
//        MMKV.defaultMMKV().encode(ConstantSign.MMKV_JSON_FROM_WHERE_JSON, JSON.toJSONString(dataListFromWhere));
//
//        method_spinnser_auth_who();

        //----------------------------------------------------------------------------------

        //----------------------------------------------------------------------------------
        //----------------------------------------------------------------------------------
        //----------------------------------------------------------------------------------
        //布局的适配器填充，下拉刷新等等；
        recyclerViewInAuthList.setLayoutManager(new MyLinearLayoutManager(this));

        authManageItemAdapter = new AuthManageItemAdapter(R.layout.authmanageadapter, mDataResources);
        recyclerViewInAuthList.setAdapter(authManageItemAdapter);

        authManageItemAdapter.notifyDataSetChanged();

        authManageItemAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                CarAttestation carAttestation = (CarAttestation) adapter.getItem(position);

                if (carAttestation != null) {
                    // : 2023-07-13 15:07 跳转到这个客户的详情页面
                    Bundle extra_bundle = new Bundle();
                    //判断 状态，如果是【待认证】的，那么就【添加认证】；
//                int currentState = carAttestation.getSatateItemIntValue();
//                if (currentState == AuthManageType.AUTH_NO.getValue()) {
//                    ActivityUtils.startActivity(extra_bundle, AuthAddSubmitActivity.class);
//                } else if (currentState == AuthManageType.AUTH_YES.getValue()) {
//                    ActivityUtils.startActivity(extra_bundle, AuthManageDetailActivity.class);
//                }

                    extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_AUTH_MANAGE_MAIN_LIST_ITEM_CLICK);

                    extra_bundle.putParcelable(ExtraKey.EXTRA_CARATTESTATION, carAttestation);

                    ActivityUtils.startActivity(extra_bundle, AuthManageDetailActivity.class);
                }

            }
        });

        authManageItemAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                CarAttestation carAttestation = (CarAttestation) adapter.getItem(position);

                if (carAttestation != null) {

                    switch (view.getId()) {

                        case R.id.textvieweditviewphoneinauth: {

                            clickButton_toCallPhone(AuthManageListActivity.this, carAttestation.getCustomerPhone(), CallHistoryBusinessType.BUSINESSTYPE_5.getIndex());

                            break;
                        }

                        default:
                            break;
                    }
                }

            }
        });

        refreshLayoutInAuthList.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        pagination_upLoad = Parameterkey.pageNum_default_first;

                        if (mDataResources != null && !mDataResources.isEmpty()) {
                            mDataResources.clear();
                        }

                        // TODO: 2023-07-13 15:11 待处理
                        getServerDatas();

                        refreshLayout.finishRefresh();
                    }
                });

            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        getServerDatas();

                        refreshLayout.finishLoadMore();
                    }
                });
            }
        });

    }

    @Override
    protected void gainDatas() {

        //是否有其他需要调用接口的地方；
        pagination_upLoad = Parameterkey.pageNum_default_first;//重置

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (authManageItemAdapter != null) {
            authManageItemAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            getServerDatas();

        } else {
            //是否有其他的执行逻辑？
            netWorkError();
            setEnableLoadmore(refreshLayoutInAuthList, false);
        }

    }

    //认证的状态； 待联系 或者 待认证
//    private void method_spinnser_auth_type() {
//
//
//    }

    //哪个机构的认证
//    private void method_spinnser_auth_who() {
//
//
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInAuthMain(EventAuthMain eventAuthMain) {

        if (eventAuthMain != null) {

            if (eventAuthMain.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_AUTH_MAIN_LIST) {

                pagination_upLoad = Parameterkey.pageNum_default_first;

                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

                //这种要清空；
                if (authManageItemAdapter != null) {
                    authManageItemAdapter.notifyDataSetChanged();
                }

                getServerDatas();

            }

        }

    }

    private void getServerDatas() {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//
        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

//        AuthManageType
//                AUTH_TO_BE_CONTACTED(0, "待联系"), //待联系
//                AUTH_TO_BE_CERTIFIED(1, "待认证"),//待认证
//                AUTH_HAS_CERTIFIED(2, "已认证"),//已认证
//                AUTH_HAS_CANCEL(3, "已取消");//已取消

        //认证状态：0:待联系;1:待认证;2:已认证;3已取消
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer
                .append(AuthManageType.AUTH_TO_BE_CONTACTED.getIndex())//待联系
                .append(",")
                .append(AuthManageType.AUTH_TO_BE_CERTIFIED.getIndex());//待认证

        map.put(Parameterkey.statusStr, stringBuffer.toString());

        // : 2023-08-11 20:43 将来做筛选条件可能用到
//        map.put(Parameterkey.latentType, latentType_upLoad);//,潜客类型 1新车;2二手车
//        map.put(Parameterkey.createsource, createsource_upLoad);//客户来源：0预约试驾；1预约看车；2自然到店；3以旧换新
//        map.put(Parameterkey.status, status_upLoad);////跟进状态：0:待联系;1:已分配;2:有意向;3无意向;4成功;5战败;6取消预约
//        map.put(Parameterkey.keyWord, keyWord_upLoad);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.GETSHOPLATENTCUSTOMERLIST_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getShopLatentCustomerList_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCarAttestationListByShop(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(AuthManageListActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<AuthManageItemOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        methodNotSuccessData(what_method, serverCode, serverMessage);

                        //{"data":"","message":"无更多数据","code":"20003"}
                        //{"data":"","message":"无数据","code":"20002"}

                        if (TextUtils.equals(serverCode, ConstantSign.RESPONSE_20003)) {
                            if (!TextUtils.isEmpty(serverMessage)) {
                                ToastUtils.showShort(serverMessage);
                            }
                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
                        if (refreshLayoutInAuthList != null) {
                            refreshLayoutInAuthList.setEnableLoadMore(true);
                        }
                    }
                }).subscribe(new Consumer<AuthManageItemOutSide>() {
                    @Override
                    public void accept(AuthManageItemOutSide authManageItemOutSide) throws Throwable {

                        if (authManageItemOutSide != null) {

                            ArrayList<CarAttestation> currentDatas = authManageItemOutSide.getDataList();

                            if (currentDatas != null && !currentDatas.isEmpty()) {
                                if (mDataResources != null) {
                                    mDataResources.addAll(currentDatas);
                                }
                            }
                        }

                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
                        if (mDataResources != null && mDataResources.isEmpty()) {
                            //同时禁用加载更多；
                            if (refreshLayoutInAuthList != null) {
                                refreshLayoutInAuthList.setEnableLoadMore(false);
                            }
                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
                        }

                        if (authManageItemAdapter != null) {
                            authManageItemAdapter.notifyDataSetChanged();
                        }

                        //给分页值
                        pagination_upLoad = authManageItemOutSide.getNextPagination();

                        //对列表改造：
                        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
                            setFinishLoadMoreWithNoMoreData(refreshLayoutInAuthList, true);
                        } else {
                            setEnableLoadmore(refreshLayoutInAuthList, true);
                        }

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；

                    }
                });

    }

    @Override
    public void methodNotSuccessData(int what_method, String serverCode, String serverMessage) {
        super.methodNotSuccessData(what_method, serverCode, serverMessage);

        switch (what_method) {

            case ConstantApi.GETSHOPLATENTCUSTOMERLIST_URL: {

                if (mDataResources != null && mDataResources.isEmpty()) {

                    if (refreshLayoutInAuthList != null) {
                        refreshLayoutInAuthList.setEnableLoadMore(false);
                    }

                    CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                            serverCode,//
                            R.drawable.errorsear,//
                            serverMessage,//
                            getString(R.string.nulldatanow));
                }

                break;
            }

            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (authManageItemAdapter != null) {
            authManageItemAdapter.notifyDataSetChanged();
            authManageItemAdapter = null;
        }

        if (mDataResources != null) {
            mDataResources = null;
        }

        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void methodBack() {
        if (ActivityUtils.isActivityAlive(this)) {
            ActivityUtils.finishActivity(this);
        }
    }
}